package com.fable.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @Author : guozhenhu
 * @date: 2023/8/28
 * @Description : 定时任务管理
 **/
@Configuration
@EnableScheduling
public class TaskSchedulerConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //实现定时任务必须要有线程池,这里即传入一个线程池,是一个自定义方法,在下面实现
        scheduledTaskRegistrar.setScheduler(schedulerThreadPool());
    }
    //里面标注方法的意思就是在这个bean destroy的时候,调用ScheduledThreadPoolExecutor类的shutdown方法优雅的关闭线程池
    @Bean(destroyMethod = "shutdown")
    public ScheduledThreadPoolExecutor schedulerThreadPool() {
               /*ScheduledThreadPoolExecutor这个类是实现了定时任务的线程池
               Runtime类解析,每一个java运行程序都有一个Runtime类实例,使当前运行程序能够与运行环境相关联,getRuntime方法返回当前
                运行程序的Runtime对象,avaliableProcessors方法返回可用处理器的数目,用返回的处理器的数目充当corePoolSize
                */
        return new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
                (r, executor) -> System.out.println("当前任务执行失败"+r));

    }
}
